<template>
	<view>
		<uni-forms ref="formRef" v-model="form" :rules="rules" :label-width="80">
			<uni-forms-item required label="账号" name="tel" >
				<uni-easyinput  v-model="form.tel" placeholder="请输入手机号" />
			</uni-forms-item>
			
			<uni-forms-item required label="密码" name="pwd" >
				<uni-easyinput type="password" v-model="form.pwd" placeholder="请输入密码" />
			</uni-forms-item>
		</uni-forms>
	</view>
	<button type="primary" @click="login">登录</button>
</template>

<script setup>
import { ref } from 'vue';

	const formRef = ref()
	const form = ref({})
	const roleIdList = ref([])
	//表单验证规则
	const rules = ref({
		tel:{
			rules:[
				{
					required:true,
					errorMessage:'账号不能为空'
				},{
					minLength:11,
					maxLength:11,
					errorMessage:'账号为11位手机号'
				},{
					validateFunction:async(rule,value,data,callback)=>{
					
						if(!/^1[35789]\d{9}$/.test(value)) {
							return callback('手机号格式不正确！')
						}else{
							return true
						};
					}
				}
			]
		},
		pwd:{
			rules:[
				{
					required:true,
					errorMessage:'账号不能为空'
				},{
					minLength:1,
					maxLength:20,
					errorMessage:'密码长度在{minLength}-{maxLength}之间'
				}
			]
		}
	})
	
	const user = ref({});
	
	//登录按钮 向后端发请求
	const login=()=>{
		formRef.value.validate()
		.then(async l =>{
			//验证成功
			const res = await uni.request({
				url: 'http://localhost:8080/user/findUser',
				method: 'GET',
				data: form.value,
				success: res => {
					if(res.data==null||res.data.length==0){
						console.log('账号或密码错误');
					}else{
						user.value = res.data
						// console.log(res.data);
						console.log(user.id);
						//将信息存入本地
						// const id = res.data[0].id.toString();
						uni.setStorageSync('id', JSON.stringify(res.data))
						
						for (let i = 0; i < res.data.length; i++) {
						
							const roleId = res.data[i].roleId;
							
							roleIdList.value.push(roleId)
						}
						/* console.log(roleIdList); */
						uni.setStorageSync('roleIdList',JSON.stringify(roleIdList))
						//转跳页面
						uni.reLaunch({ url: '/pages/zhuye/zhuye' })
					}
					
				},
				fail: () => {},
				complete: () => {}
			});
		})
	}
</script>

<style>
	
</style>
